package fr.castorflex.CshopFlex;

import java.io.IOException;
import java.util.ArrayList;

import org.apache.http.client.ClientProtocolException;
import org.json.JSONException;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;
import android.widget.ViewFlipper;
import fr.castorflex.CshopFlex.Listeners.MyCancelListener;
import fr.castorflex.CshopFlex.Listeners.MyListViewListener;
import fr.castorflex.CshopFlex.Model.Item;
import fr.castorflex.CshopFlex.Utilities.AnimationHelper;
import fr.castorflex.CshopFlex.Utilities.JSONOperations;
import fr.castorflex.CshopFlex.Utilities.Parameters;
import fr.castorflex.CshopFlex.Utilities.Utils;
import fr.castorflex.CshopFlex.Views.SearchProductsAdapter;

public class MainActivity extends Activity implements OnClickListener,
		OnEditorActionListener {

	public static int NUM_SCREEN;

	private ViewFlipper flipper;

	// screen 1////////////////////////////////////////
	private EditText etSearch;
	private Button bSearch;

	private ListView lvProducts;
	private SearchProductsAdapter adapterProducts;

	private ProgressBar progressBar;
	private static Thread threadSearchProducts;
	private Handler handler;
	// ////////////////////////////////////////////////

	// screen 2/////////////////////////////
	private TextView tvSpecificItemTitle;
	// /////////////////////////////////////

	ProgressDialog d;
	private static boolean started = false;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);

		NUM_SCREEN = 1;
		adapterProducts = new SearchProductsAdapter();

		flipper = (ViewFlipper) findViewById(R.id.viewFlipper1);

		tvSpecificItemTitle = (TextView) findViewById(R.id.textViewSpecificItemTitle);
		etSearch = (EditText) findViewById(R.id.editTextSearch);
		bSearch = (Button) findViewById(R.id.buttonSearch);
		lvProducts = (ListView) findViewById(R.id.listViewProducts);
		progressBar = (ProgressBar) findViewById(R.id.progressBarSearchMoreProducts);
		
		progressBar.setVisibility(ProgressBar.GONE);
		lvProducts.setClickable(true);
		lvProducts.setAdapter(adapterProducts);
		
		bSearch.setOnClickListener(this);
		MyListViewListener listViewListener = new MyListViewListener(this,
				lvProducts);

		etSearch.setOnEditorActionListener(this);
		lvProducts.setOnItemClickListener(listViewListener);
		lvProducts.setOnScrollListener(listViewListener);

	}

	@Override
	public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
		if ((actionId == EditorInfo.IME_ACTION_SEARCH))
			if (!etSearch.getText().toString().isEmpty()) {
				SearchForProducts(etSearch.getText().toString());
				closeKeyboard(etSearch.getWindowToken());
			}

		return false;
	}

	@Override
	public void onClick(View v) {
		if (!etSearch.getText().toString().isEmpty()) {
			SearchForProducts(etSearch.getText().toString());
			closeKeyboard(etSearch.getWindowToken());
		}

	}

	public void closeKeyboard(IBinder binder) {
		InputMethodManager imm = (InputMethodManager) this
				.getSystemService(Context.INPUT_METHOD_SERVICE);
		imm.hideSoftInputFromWindow(binder, 0);
	}

	private void SearchForProducts(final String stringToSearch) {

		handler = new Handler() {
			@Override
			public void handleMessage(android.os.Message msg) {
				if (msg.what == Parameters.CANCEL_RESEARCH) {
					Log.i("mainactibity", "interruption du thread");
					threadSearchProducts.interrupt();
				} else if (msg.what == Parameters.RESEARCH_FINISHED) {
					d.dismiss();
					lvProducts.setAdapter(adapterProducts);
				}

			};
		};

		// progress Dialog////////////////////////////////////////
		d = new ProgressDialog(this);
		d.setCancelable(true);
		d.setOnCancelListener(new MyCancelListener(handler));
		d.setTitle("Loading");
		TextView tv = new TextView(d.getContext());
		tv.setText("Please wait while loading...");
		d.setView(tv);
		d.show();
		// ////////////////////////////////////////////////////

		threadSearchProducts = new Thread(new Runnable() {

			@Override
			public void run() {
				String request = getRequest(stringToSearch);
				getResponse(request);

				Message m = handler.obtainMessage();
				m.what = Parameters.RESEARCH_FINISHED;
				handler.sendMessage(m);
			}

		});

		threadSearchProducts.start();

	}

	private void getResponse(String request) {
		ArrayList<Item> list = null;

		try {
			list = JSONOperations.getItemsFromURL(request);

		} catch (ClientProtocolException e) {

			e.printStackTrace();
		} catch (IOException e) {

			e.printStackTrace();
		} catch (JSONException e) {

			e.printStackTrace();
		}

		adapterProducts = new SearchProductsAdapter(this, list);

	}

	private String getRequest(String stringToSearch) {
		stringToSearch = stringToSearch.replace(" ", "+");

		StringBuilder stringBuilder = new StringBuilder();
		stringBuilder.append(Parameters.NAME_HOST);
		stringBuilder.append(Parameters.PATH_SEARCH_PRODUCTS_METHOD);
		stringBuilder.append(Parameters.PARAMETER_REQUEST_NAME_KEY);
		stringBuilder.append("=");
		stringBuilder.append(Parameters.API_KEY);
		stringBuilder.append("&");
		stringBuilder.append(Parameters.PARAMETER_REQUEST_NAME_COUNTRY);
		stringBuilder.append("=");
		stringBuilder.append(Parameters.PARAMETER_REQUEST_ATTR_COUNTRY);
		stringBuilder.append("&");
		stringBuilder.append(Parameters.PARAMETER_REQUEST_NAME_QUERY);
		stringBuilder.append("=");
		stringBuilder.append(stringToSearch);
		stringBuilder.append("&");
		stringBuilder.append(Parameters.PARAMETER_REQUEST_NAME_ALT);
		stringBuilder.append("=");
		stringBuilder.append(Parameters.PARAMETER_REQUEST_ATTR_ALT);

		return stringBuilder.toString();
	}

	@Override
	public void onBackPressed() {
		if (NUM_SCREEN == 2) {
			flipper.setInAnimation(AnimationHelper.inFromLeftAnimation());
			flipper.setOutAnimation(AnimationHelper.outToRightAnimation());
			// Flip!
			flipper.showPrevious();
			NUM_SCREEN = 1;
		} else
			super.onBackPressed();
	}

	@Override
	protected void onDestroy() {
		if (adapterProducts != null)
			adapterProducts.imageLoader.stopThread();
		lvProducts.setAdapter(null);
		super.onDestroy();
	}

	public void displaySpecificItem(Item item) {
		if (NUM_SCREEN == 1) {
			// Set the animation
			flipper.setInAnimation(AnimationHelper.inFromRightAnimation());
			flipper.setOutAnimation(AnimationHelper.outToLeftAnimation());
			// Flip!
			flipper.showNext();
			NUM_SCREEN = 2;
		}
		tvSpecificItemTitle.setText(item.getNom());
	}

	public void launchThreadLoadMoreProducts() {
		if (!started) {
			started = true;
			progressBar.setVisibility(ProgressBar.VISIBLE);
			new AddMoreDataTask().execute();
		}
	}

	public class AddMoreDataTask extends AsyncTask<Void, Void, Void> {

		@Override
		protected Void doInBackground(Void... params) {
			try {
				
				adapterProducts.loadMoreProducts();
			} catch (ClientProtocolException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			return null;
		}

		@Override
		protected void onPostExecute(Void result) {
			adapterProducts.notifyDataSetChanged();
			progressBar.setVisibility(ProgressBar.GONE);
			super.onPostExecute(result);
			started = false;
		}

	}

}
